package com.work.studio.net;

import android.net.ParseException;
import android.util.Log;

import com.work.studio.entitys.BaseApiEntity;

import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;

public abstract class ConsumerMy<T> implements Observer<T> {

    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onComplete() {

    }

    @Override
    public void onNext(T t) {
        if (t instanceof BaseApiEntity) {
            BaseApiEntity entity = (BaseApiEntity) t;
            if (entity != null && "0".equals(entity.getCode())) {
                _onSuccess(t);
            }
            else {
                _onError(entity.getCode(), entity.getMsg());
            }
        } else {
            _onSuccess(t);
        }
    }

    @Override
    public void onError(Throwable e) {
        String message = "";
        if (e instanceof JSONException || e instanceof ParseException) {
            message = "解析错误";
        } else if (e instanceof ConnectException) {
            message = "连接失败";
        } else if (e instanceof ConnectTimeoutException || e instanceof SocketTimeoutException) {
            message = "连接超时";
        } else if (e instanceof HttpException) {
            message = "连接服务器错误-" + ((HttpException) e).code();
        } else {
            message = "网络连接不可用，请检查网络";
            Log.e("UnKnow", ""+e.getLocalizedMessage());
        }
        _onError("onError", message);
    }

    /**
     * 请求成功
     *
     * @param t 请求返回体，如果返回体是 BaseApiEntity 则无需判断 isRetCode ,因为在前面的逻辑已经判断过了，可以直接调用 getData()
     */
    protected void _onSuccess(T t) {

    }

    /**
     * 请求接口失败或业务失败
     *
     * @param errorCode    为 0 时表示接口失败，为其他时表示业务层面上的失败
     * @param errorMessage 错误信息
     */
    protected void _onError(String errorCode, String errorMessage) {

    }
}
